package xt.outfood.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 定义处理全局的异常。通过RestControllerAdvice注解配置要处理异常的类,
 * 此处主要处理账号添加时账号已经存在问题
 * @author 小小爱欧
 * @date 2022/7/20 11:35
 *
 */
@RestControllerAdvice(annotations={RestController.class, Controller.class})
@Slf4j
public class GlobalException  {
    /**
     * 异常处理方法，主要处理SQLIntegrityConstraintViolationException这种异常
     * @param exception
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.info(exception.getMessage());
        //判断异常信息是否包含异常信息关键字“Duplicate entry”
        if (exception.getMessage().contains("Duplicate entry")){
            String[] split=exception.getMessage().split(" ");
            String s = split[2];
            return Result.error(s+"已存在，保存失败");
        }
        return Result.error("错误丢到外星去了，请重新尝试..................");

    }

    /**
     * 此处主要处理自定义的CustomException异常，用于捕获CustomException抛出的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result<String> customexceptionHandler(CustomException exception){
        log.info(exception.getMessage());
        return Result.error(exception.getMessage());

    }
}
